﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Text;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.ApiService.Controllers
{
    /// <summary>
    /// 系统配置API
    /// </summary>
    public class SysConfigApiController : BaseApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(SysConfigApiController));
        private readonly SysConfigBLL _sysConfigBll = new SysConfigBLL();
        private readonly SysPayDiscountConfigBLL _sysPayDiscountConfigBll = new SysPayDiscountConfigBLL();

        //POST api/SysConfigApi/GetSysConfig
        /// <summary>
        /// 获取系统配置参数
        /// </summary>
        /// <returns>返回系统配置信息（含基础配置、立减配置）</returns>
        [HttpPost]
        public Result<SysConfigDto> GetSysConfig()
        {
            var checkResult = CheckPermission("SysConfigController | GetSysConfig");
            if (!checkResult.Status)
            {
                return new Result<SysConfigDto>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }

            try
            {
                var lsSysConfig = _sysConfigBll.GetModelList();
                if (lsSysConfig == null || lsSysConfig.Count == 0)
                {
                    return new Result<SysConfigDto>
                    {
                        Status = false,
                        Message = "No sysconfig data in database",
                        Data = null
                    };
                }

                var lsSysPayConfig = _sysPayDiscountConfigBll.GetModelList();

                return new Result<SysConfigDto>
                {
                    Status = true,
                    Message = "Success",
                    Data = new SysConfigDto
                    {
                        SysConfigInfo = lsSysConfig[0],
                        SysPayDiscountConfigInfo = lsSysPayConfig
                    }
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigController | GetSysConfig | Exception: " + ex.Message + ex.StackTrace);
                return new Result<SysConfigDto>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }
        }

        //POST api/SysConfigApi/GetOrderDiscountByConfig
        /// <summary>
        /// 获取系统立减值
        /// </summary>
        /// <param name="orderDiscoutPrice">立减前价格</param>
        /// <param name="consumerId">用户ID</param>
        /// <param name="verifyCode">校验码</param>
        /// <returns>返回系统配置信息（含基础配置、立减配置）</returns>
        [HttpPost]
        public Result<decimal> GetOrderDiscountByConfig(decimal orderDiscoutPrice, int consumerId, string verifyCode)
        {
            var checkResult = CheckPermission("SysConfigController | GetOrderDiscountByConfig");
            if (!checkResult.Status)
            {
                return new Result<decimal>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = 0
                };
            }

            #region 数据合法性检查
            if (string.IsNullOrWhiteSpace(verifyCode) || orderDiscoutPrice <= 0)
            {
                _fileLog.Error("SysConfigController | GetOrderDiscountByConfig | Error: Invalid paramter.");
                return new Result<decimal>
                {
                    Status = false,
                    Message = "Invalid paramter",
                    Data = 0
                };
            }

            var strLocalEncodeResult = EncryptionLib.Encrypt(orderDiscoutPrice.ToString() + consumerId);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("SysConfigController | GetOrderDiscountByConfig | Error: Invalid verify code.");
                return new Result<decimal>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = 0
                };
            }
            #endregion

            try
            {
                var lsSysConfig = _sysConfigBll.GetModelList();
                if (lsSysConfig == null || lsSysConfig.Count == 0)
                {
                    return new Result<decimal>
                    {
                        Status = false,
                        Message = "No sysconfig data in database",
                        Data = 0
                    };
                }

                if (!lsSysConfig[0].IsPayDiscount || orderDiscoutPrice < lsSysConfig[0].MinPayValueOfOrder)
                {
                    return new Result<decimal>
                    {
                        Status = true,
                        Message = "Cannot support pay-discount of this order.",
                        Data = 0
                    };
                }

                var discountValue = _sysPayDiscountConfigBll.GetRandomPayDiscount(consumerId, orderDiscoutPrice);
                var dCurrentDiscountAmount = OrdersBLL.Instance.GetTotalPayDiscountAmount(DateTime.Now.Date,
                    DateTime.Now.Date.AddDays(1));

                var dcLeftDiscountValue = lsSysConfig[0].DayMaxPayDiscount - dCurrentDiscountAmount;
                if (dcLeftDiscountValue <= 0)
                {
                    return new Result<decimal>
                    {
                        Status = true,
                        Message = "Cannot to discount 'cause no left value",
                        Data = 0
                    };
                }

                if (discountValue > Convert.ToDouble(dcLeftDiscountValue))
                {
                    return new Result<decimal>
                    {
                        Status = true,
                        Message = "Success",
                        Data = dcLeftDiscountValue
                    };
                }
                return new Result<decimal>
                {
                    Status = true,
                    Message = "Success",
                    Data = Convert.ToDecimal(discountValue)
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigController | GetOrderDiscountByConfig | Exception: " + ex.Message + ex.StackTrace);
                return new Result<decimal>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = 0
                };
            }
        }

        //POST api/SysConfigApi/AddNewRedEnvolopeRecordForLjActivity
        /// <summary>
        /// 添加第三方红包发送记录，并更新平台金额值
        /// </summary>
        /// <param name="mcId"></param>
        /// <param name="userOpendId">用户OPENID</param>
        /// <param name="redValue"></param>
        /// <param name="wechatPaySerialNo"></param>
        /// <param name="activityCode"></param>
        /// <param name="verifyCode"></param>
        /// <returns></returns>
        [HttpPost]
        public Result<decimal> AddNewRedEnvolopeRecordForLjActivity(string mcId, string userOpendId, int redValue,
            string wechatPaySerialNo, string activityCode, string verifyCode)
        {
            var sysMoneyBll = new SysMoneyBLL();
            var moneyChangeRecordBll = new SysMoneyChangeRecordBLL();


            var checkResult = CheckPermission("SysConfigController | AddNewRedEnvolopeRecordForLjActivity");
            if (!checkResult.Status)
            {
                return new Result<decimal>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = 0
                };
            }

            #region 数据合法性检查

            if (string.IsNullOrWhiteSpace(mcId) || string.IsNullOrWhiteSpace(userOpendId) || redValue <= 0 ||
                string.IsNullOrWhiteSpace(wechatPaySerialNo) || string.IsNullOrWhiteSpace(activityCode) ||
                string.IsNullOrWhiteSpace(verifyCode))
            {
                _fileLog.Error("SysConfigController | AddNewRedEnvolopeRecordForLjActivity | Error: Invalid paramter.");
                return new Result<decimal>
                {
                    Status = false,
                    Message = "Invalid paramter",
                    Data = 0
                };
            }

            var strEncodeSource = mcId + userOpendId + redValue + wechatPaySerialNo + activityCode;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strEncodeSource, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("SysConfigController | AddNewRedEnvolopeRecordForLjActivity | Error: Invalid verify code.");
                return new Result<decimal>
                {
                    Status = false,
                    Message = "Invalid verify code",
                    Data = 0
                };
            }
            #endregion

            try
            {
                var wechatUserInfo = GetMxApiWechatUserInfo(userOpendId, mcId);
                if (wechatUserInfo == null)
                {
                    return new Result<decimal>
                    {
                        Status = false,
                        Message = "无效McId或OpenId",
                        Data = 0
                    };
                }

                var localProjectInfo = MatrixCloudProjectInfoBLL.Instance.GetModelByPjMcId(mcId);
                if (localProjectInfo == null || localProjectInfo.Id == 0)
                {
                    return new Result<decimal>
                    {
                        Status = false,
                        Message = "无效McId",
                        Data = 0
                    };
                }

                var lsSysMoneyInfo = sysMoneyBll.GetModelList();
                if (lsSysMoneyInfo == null || lsSysMoneyInfo.Count == 0 || lsSysMoneyInfo[0].Id == 0)
                {
                    return new Result<decimal>
                    {
                        Status = false,
                        Message = "Cannot update the sysmoney info",
                        Data = 0
                    };
                }

                var moneyChangeRecord = new SysMoneyChangeRecord
                {
                    MxProjectInfoId = localProjectInfo.Id,
                    BeforeMoney = lsSysMoneyInfo[0].CurrentCash,
                    AfterMoney = (lsSysMoneyInfo[0].CurrentCash - redValue) < 0 ? 0 : lsSysMoneyInfo[0].CurrentCash - redValue,
                    ChangeSource = 1,
                    ChangeSerialNumber = wechatPaySerialNo,
                    ChangeMoney = redValue,
                    OperaOpenId = userOpendId,
                    OperaSource = 2,
                    OperaResult = 2,
                    OutActivityCode = activityCode,
                    AddTime = DateTime.Now,
                    IsDelete = false
                };

                if (moneyChangeRecordBll.Add(moneyChangeRecord) > 0)
                {
                    lsSysMoneyInfo[0].CurrentCash = moneyChangeRecord.AfterMoney;
                    lsSysMoneyInfo[0].UpdateTime = DateTime.Now;
                    sysMoneyBll.Update(lsSysMoneyInfo[0]);
                }

                return new Result<decimal>
                {
                    Status = true,
                    Message = "Success",
                    Data = moneyChangeRecord.AfterMoney
                };

            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigController | AddNewRedEnvolopeRecordForLjActivity | Exception: " + ex.Message + ex.StackTrace);
                return new Result<decimal>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = 0
                };
            }
        }

        #region 系统消息

        /// <summary>
        /// 系统消息
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="consumerId">用户id</param>
        /// <param name="verifyCode">加密验证  </param>
        /// <returns></returns>
        [HttpPost]
        public Result<string> SysMessage(int pageIndex, int consumerId, string verifyCode)
        {
            var checkResult = CheckPermission("SysConfigApiController | SysMessage");
            if (!checkResult.Status)
            {
                return new Result<string>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = pageIndex.ToString(CultureInfo.InvariantCulture) + consumerId.ToString(CultureInfo.InvariantCulture);
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("SysConfigApiController | SendSMS | Error: Invalid verify code.");
                return new Result<string>
                {
                    Status = false,
                    Message = "Invalid verify verifyCode",
                    Data = null
                };
            }
            try
            {
                var cloudUser = ConsumerBLL.Instance.GetModel(consumerId);
                if (cloudUser == null)
                {
                    _fileLog.Error("SysConfigApiController | SendSMS | 用户未授权登录 ");
                    return new Result<string>
                    {
                        Status = false,
                        Message = "用户不存在",
                        Data = null
                    };
                }
                JsonModel.PageList<SysMessage> result = SysMessageBLL.Instance.GetSysMessageList(pageIndex, PageSize,
                    cloudUser.Id);
                var strEncodedOrderInfo = EncryptionLib.Encrypt(JsonTool.ObjToJson(result), Encoding.UTF8);
                return new Result<string>
                {
                    Status = true,
                    Message = "Success",
                    Data = strEncodedOrderInfo
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigApiController | SysMessage | Exception " + ex.Message + ex.StackTrace);
                return new Result<string>
                            {
                                Status = false,
                                Message = ex.Message,
                                Data = null
                            };
            }
        }

        /// <summary>
        /// 系统消息详情
        /// </summary>
        /// <param name="id">消息id</param>
        /// <returns></returns>
        [HttpPost]
        public Result<SysMessage> SysMessageDetail(int id)
        {
            var checkResult = CheckPermission("SysConfigApiController | SysMessageDetail");
            if (!checkResult.Status)
            {
                return new Result<SysMessage>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            try
            {
                var result = SysMessageBLL.Instance.GetModel(id);
                return new Result<SysMessage>
                {
                    Status = true,
                    Message = "Success",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigApiController | SysMessage | Exception " + ex.Message + ex.StackTrace);
                return new Result<SysMessage>
                                  {
                                      Status = false,
                                      Message = ex.Message,
                                      Data = null
                                  };
            }
        }

        #endregion

        #region 发送短信验证码

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="mobile">手机号码</param>
        /// <param name="userActionSource">发送对象用户行为来源 发送对象用户行为来源0商家账户注册,1用户注册,2商家充值/提现3用户充值/提现4商家爱审核5卡卷审核6用户密码找回,7卡卷领取,99其他</param>
        /// <param name="userId">请求接口用户id</param>
        /// <param name="verifyCode"></param>
        /// <returns></returns>
        /// <remarks>userActionSource (CommonEnum.SmsRecordUserActionSource)</remarks>
        [HttpPost]
        public Result<string> SendSMS(string mobile, int userActionSource, int userId, string verifyCode)
        {
            var checkResult = CheckPermission("SysConfigApiController | SendSMS");
            if (!checkResult.Status)
            {
                return new Result<string>
                {
                    Status = checkResult.Status,
                    Message = checkResult.Message,
                    Data = null
                };
            }
            var strSouceToEncode = mobile + userActionSource + userId;
            var strLocalEncodeResult = EncryptionLib.Encrypt(strSouceToEncode, Encoding.UTF8);
            if (strLocalEncodeResult != verifyCode)
            {
                _fileLog.Error("SysConfigApiController | SendSMS | Error: Invalid verify code.");
                return new Result<string>
                {
                    Status = false,
                    Message = "Invalid verify verifyCode",
                    Data = null
                };
            }
            string result = string.Empty;
            string code=StringExtension.GetCode(4);
            try
            {
                bool isok = SmsRecordBLL.Instance.SendSms(mobile, "你的验证码是：" + code, CommonEnum.SmsRecordSendFrom.WeiXin, (CommonEnum.SmsRecordUserActionSource)userActionSource, code, MsgExpireTime, userId);
                if (isok)
                {
                    return new Result<string>
                    {
                        Status = true,
                        Message = "Success",
                        Data = code
                    };
                }
                else
                {
                    return new Result<string>
                    {
                        Status = false,
                        Message = "短信接口Error",
                        Data = result
                    };
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("SysConfigApiController | SendSMS |Exception:" + ex.Message+ex.StackTrace);
                return new Result<string>
                {
                    Status = false,
                    Message = ex.Message,
                    Data = null
                };
            }

        }
        #endregion

    }
}
